<template>
  <el-upload
    ref="upload"
    name="file"
    :action="serverPath + basePath"
    :headers="token"
    :accept="acceptPrefix"
    :data="queryParam"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :before-upload="beforeUpload"
    :on-progress="onProgress"
    :on-error="onError"
    :on-change="onChange"
    :on-success="onSuccess"
    :multiple="multiple"
    :list-type="listType"
    :limit="limit"
    :disabled="disabled"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <div class="left" v-if="!disabled">
      <el-button size="mini" plain type="primary" icon="el-icon-plus" :disabled="loading" @click="clearTip">{{ text }}</el-button>
<!--      <el-progress v-if="loading" :percentage="percent"></el-progress>-->
    </div>
    <p v-if="tip" slot="tip" class="red p0 m0 font-12">{{ tip }}</p>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getSettingMap } from '@/api/sys'
import { deleteTemp } from '@/api/uploader'

const basePath = process.env.VUE_APP_BASE_API

export default {
  name: 'Uploader',
  props: {
    url: String,
    listType: {
      type: String,
      default: 'text'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default: '选择文件'
    },
    limit: {
      type: Number,
      default: 1
    },
    param: {
      type: Object,
      default: () => {}
    },
    disabled:{
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    attach: {
      type: Array,
      default: () => []
    },
    accept: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      basePath: '/sys/attach/uploadTemp',
      serverPath: basePath === '/' ? '' : basePath,
      loading: false,
      percent: 0,
      tip: null,
      fileList: [],
      fileIds: this.attach,
      cfg: {
        maxFileSize: 10,
        acceptType: ''
      },
      queryParam: {
        name: null
      }
    }
  },
  methods: {
    clearFile(){
      this.$refs.upload.clearFiles()
      this.clearTip()
    },
    clearTip(){
      this.tip = null
    },
    handleRemove(file, fileList) {
      //console.log(file, fileList);
    },
    handlePreview(file) {
      //console.log(file);
    },
    handleExceed(files, fileList) {
      this.tip =(`最多上传${this.limit}个文件`);
    },
    beforeUpload(file) {
      this.beginUpload()
      //console.log(file)
      this.queryParam.name = file.name
      return true;
    },
    beforeRemove(file, fileList) {
      let b = this.$confirm(`确定移除 ${ file.name }？`);
      if(b && file.uuid){
        deleteTemp(file.uuid).then(()=>{
          this.$util.removeArrObj(this.value,file.uuid)
          this.$emit('onChange')
        })
      }
      return b;
    },
    onChange(event, file, fileList) {
      this.$emit('onChange')
    },
    onProgress(event, file, fileList) {
      //console.log('onProgress',event);
      this.percent = event.percent
    },
    onError(err, file, fileList) {
      this.finishUpload()
      //console.log('onError',err, file, fileList);
      this.removeUpload(file,fileList)
    },
    onSuccess(response, file, fileList) {
      let uuid = response.uuid
      //console.log('onSuccess',response)
      if(response.code !== 200 || !uuid){
        this.tip = response.msg || '上传失败'
        this.removeUpload(file,fileList)
      }else{
        file.uuid = uuid
        this.value.push(uuid)
      }
      this.finishUpload()
    },
    removeUpload(file,fileList){
      let that = this
      setTimeout(function(){
        that.$util.removeArrObj(fileList,file)
      },500)
    },
    beginUpload(){
      this.loading = true
      this.percent = 0
    },
    finishUpload(){
      this.percent = 100
      this.$emit('finish')
      let that = this
      setTimeout(function(){
        that.loading = false
      },500)
    },
  },
  computed: {
    token() {
      return {
        appToken: getToken()
      }
    },
    acceptPrefix(){
      let arr = this.cfg.acceptType.split(',')||'jpg'
      if(this.accept.length > 0){
        arr = [].concat(this.accept)
      }
      for (let i = 0; i < arr.length; i++) {
        if(this.$util.isNotBlank(arr[i])){
          arr[i] = '.' + arr[i]
        }
      }
      return arr.join(',')
    },
  },
  watch: {
    attach: function(v){
      console.log('watch attach',v)
      if(v){
        for (let i = 0; i < v.length; i++) {
          this.fileList.push({name:'',url:this.serverPath+'/sys/attach/pubGet?id='+v[i]+'&dt='+new Date().getTime()})
        }
      }
      console.log(this.fileList)
    }
  },
  mounted() {
    getSettingMap('uploader').then(r => {
      this.cfg = r
    })
  },
  activated() {

  }
}
</script>

<style scoped>

</style>
